package com.lagou.edu.factory;

import com.lagou.edu.anno.CustomAutowired;
import com.lagou.edu.anno.CustomService;
import com.lagou.edu.anno.CustomTransactional;
import com.lagou.edu.service.TransferService;
import com.lagou.edu.utils.ConnectionUtils;
import com.lagou.edu.utils.TransactionManager;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.reflections.Reflections;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author 应癫
 *
 * 工厂类，生产对象（使用反射技术）
 */
public class BeanFactory {

    /**
     * 任务一：读取解析xml，通过反射技术实例化对象并且存储待用（map集合）
     * 任务二：对外提供获取实例对象的接口（根据id获取）
     */

    private static Map<String,Object> map = new HashMap<>();  // 存储对象


    static {
        //实例化ConnectionUtils
        try {
            Class<?> connectionUtilsClass = Class.forName("com.lagou.edu.utils.ConnectionUtils");
            Object connectionUtilsObj = connectionUtilsClass.newInstance();
            map.put("connectionUtils", connectionUtilsObj);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

        //实例化TransactionManager
        try {
            Class<?> transactionManagerClass = Class.forName("com.lagou.edu.utils.TransactionManager");
            Object transactionManagerObj = transactionManagerClass.newInstance();

            PropertyDescriptor transactionManagerPropertyDescriptor =
                    new PropertyDescriptor("connectionUtils", transactionManagerClass);
            Method transactionManagerWriteMethod = transactionManagerPropertyDescriptor.getWriteMethod();
            transactionManagerWriteMethod.invoke(transactionManagerObj, (ConnectionUtils)map.get("connectionUtils"));
            map.put("transactionManager", transactionManagerObj);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

        //实例化ProxyFactory
        try {
            Class<?> proxyFactoryClass = Class.forName("com.lagou.edu.factory.ProxyFactory");
            Object proxyFactoryObj = proxyFactoryClass.newInstance();

            PropertyDescriptor proxyFactoryPropertyDescriptor =
                    new PropertyDescriptor("transactionManager", proxyFactoryClass);
            Method proxyFactoryWriteMethod = proxyFactoryPropertyDescriptor.getWriteMethod();
            proxyFactoryWriteMethod.invoke(proxyFactoryObj, (TransactionManager)map.get("transactionManager"));
            map.put("proxyFactory", proxyFactoryObj);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        Reflections reflections = new Reflections("com.lagou.edu.service.impl");
        Set<Class<?>> serviceSet = reflections.getTypesAnnotatedWith(CustomService.class);
        for(Class<?> clazz : serviceSet) {
            Object serviceBean = null;
            try {
                serviceBean = clazz.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            Field[] fields = clazz.getDeclaredFields();
            for(Field field : fields) {
                CustomAutowired customAutowired = field.getAnnotation(CustomAutowired.class);
                if(customAutowired != null) {
                    try {
                        Class<?> daoImplClass = Class.forName("com.lagou.edu.dao.impl.JdbcAccountDaoImpl");
                        Object daoImplObj = daoImplClass.newInstance();
                        String fieldName = (customAutowired.value().equals("")) ? field.getName() : customAutowired.value();
                        PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldName, clazz);
                        Method writeMethod = propertyDescriptor.getWriteMethod();
                        writeMethod.invoke(serviceBean, daoImplObj);

                        //注入ConnectionUtils到AccountDao中
                        PropertyDescriptor accountDaoPropertyDescriptor =
                                new PropertyDescriptor("connectionUtils", daoImplClass);
                        Method accountDaoWriteMethod = accountDaoPropertyDescriptor.getWriteMethod();
                        accountDaoWriteMethod.invoke(daoImplObj, (ConnectionUtils)map.get("connectionUtils"));
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IntrospectionException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }
            CustomService customService = clazz.getAnnotation(CustomService.class);
            String serviceName = (customService.value().equals("")) ? clazz.getSimpleName() : customService.value();
            map.put(serviceName, serviceBean);
        }

        for(Map.Entry<String, Object> serviceBean : map.entrySet()) {
            Object value = serviceBean.getValue();
            Class<?> clazz = value.getClass();
            CustomTransactional customTransactional = clazz.getAnnotation(CustomTransactional.class);
            if(customTransactional != null) {
                Class<?>[] classes = clazz.getInterfaces();
                String key = serviceBean.getKey();
                if(classes != null && classes.length > 0) {
                    map.put(key, ((ProxyFactory)map.get("proxyFactory")).getJdkProxy((TransferService)map.get(key)));
                } else {
                    map.put(key, ((ProxyFactory)map.get("proxyFactory")).getCglibProxy((TransferService)map.get(key)));
                }
            }
        }

        /*// 任务一：读取解析xml，通过反射技术实例化对象并且存储待用（map集合）
        // 加载xml
        InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
        // 解析xml
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> beanList = rootElement.selectNodes("//bean");
            for (int i = 0; i < beanList.size(); i++) {
                Element element =  beanList.get(i);
                // 处理每个bean元素，获取到该元素的id 和 class 属性
                String id = element.attributeValue("id");        // accountDao
                String clazz = element.attributeValue("class");  // com.lagou.edu.dao.impl.JdbcAccountDaoImpl
                // 通过反射技术实例化对象
                Class<?> aClass = Class.forName(clazz);
                Object o = aClass.newInstance();  // 实例化之后的对象

                // 存储到map中待用
                map.put(id,o);

            }

            // 实例化完成之后维护对象的依赖关系，检查哪些对象需要传值进入，根据它的配置，我们传入相应的值
            // 有property子元素的bean就有传值需求
            List<Element> propertyList = rootElement.selectNodes("//property");
            // 解析property，获取父元素
            for (int i = 0; i < propertyList.size(); i++) {
                Element element =  propertyList.get(i);   //<property name="AccountDao" ref="accountDao"></property>
                String name = element.attributeValue("name");
                String ref = element.attributeValue("ref");

                // 找到当前需要被处理依赖关系的bean
                Element parent = element.getParent();

                // 调用父元素对象的反射功能
                String parentId = parent.attributeValue("id");
                Object parentObject = map.get(parentId);
                // 遍历父对象中的所有方法，找到"set" + name
                Method[] methods = parentObject.getClass().getMethods();
                for (int j = 0; j < methods.length; j++) {
                    Method method = methods[j];
                    if(method.getName().equalsIgnoreCase("set" + name)) {  // 该方法就是 setAccountDao(AccountDao accountDao)
                        method.invoke(parentObject,map.get(ref));
                    }
                }

                // 把处理之后的parentObject重新放到map中
                map.put(parentId,parentObject);

            }


        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }*/

    }


    // 任务二：对外提供获取实例对象的接口（根据id获取）
    public static  Object getBean(String id) {
        return map.get(id);
    }

}
